package com.dify.knowledge.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(DifyApiException.class)
    public ResponseEntity<Map<String, Object>> handleDifyApiException(DifyApiException e) {
        log.error("Dify API调用异常: {}", e.getMessage(), e);
        return buildErrorResponse("DIFY_API_ERROR", e.getMessage(), HttpStatus.BAD_GATEWAY);
    }

    @ExceptionHandler(DocumentProcessingException.class)
    public ResponseEntity<Map<String, Object>> handleDocumentProcessingException(DocumentProcessingException e) {
        log.error("文档处理异常: {}", e.getMessage(), e);
        return buildErrorResponse("DOCUMENT_PROCESSING_ERROR", e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(RatingLimitException.class)
    public ResponseEntity<Map<String, Object>> handleRatingLimitException(RatingLimitException e) {
        log.warn("评分限制异常: {}", e.getMessage());
        return buildErrorResponse("RATING_LIMIT_ERROR", e.getMessage(), HttpStatus.TOO_MANY_REQUESTS);
    }

    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity<Map<String, Object>> handleUnauthorizedException(UnauthorizedException e) {
        log.warn("未授权访问: {}", e.getMessage());
        return buildErrorResponse("UNAUTHORIZED", e.getMessage(), HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleGenericException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return buildErrorResponse("INTERNAL_ERROR", "系统内部错误，请稍后重试", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    private ResponseEntity<Map<String, Object>> buildErrorResponse(String code, String message, HttpStatus status) {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("code", code);
        errorResponse.put("message", message);
        errorResponse.put("timestamp", LocalDateTime.now());
        return ResponseEntity.status(status).body(errorResponse);
    }
}
